//
// Copyright (c) 2005 BroadVision, Inc. All rights reserved.
//
// This software is copyrighted.  Under the copyright laws, this software
// may not be copied, in whole or in part, without prior written consent
// of BroadVision, Inc. or its assignees.  This software is provided under
// the terms of a license between BroadVision and the recipient, and its
// use is subject to the terms of that license.
//
// This software may be protected by one or more U.S. and International
// patents.  Certain applications of BroadVision One-To-One software are
// covered by U.S. patent 5,710,887.
//
// TRADEMARKS: BroadVision and BroadVision One-To-One are registered
// trademarks of BroadVision, Inc., in the United States and the European
// Community, and are trademarks of BroadVision, Inc., in other
// countries.  The BroadVision logo, is a trademark of BroadVision, Inc.,
// in the United States and other countries. Additionally, IONA and Orbix
// are trademarks of IONA Technologies, Ltd.  RSA, MD5, and RC2 are
// trademarks of RSA Data Security, Inc.
//

package com.broadvision.manage.common.tools.action.user;

import java.security.Principal;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.Globals;

import com.broadvision.web.util.ViewDynaBean;
import com.broadvision.portal.services.PortalVisitor;
import com.broadvision.system.accesscontrol.client.ACObjectID;
import com.broadvision.system.accesscontrol.client.AccessManager;
import com.broadvision.visitor.client.Visitor;
import com.broadvision.visitor.client.VisitorGroupManager;
import com.broadvision.visitor.interfaces.VisitorGroup;

import com.broadvision.manage.common.tools.user.UserProfile;
import com.broadvision.manage.tools.action.BaseAction;

/**
 * Retrieves user's groups
 */
public class GroupViewAction extends BaseAction {

  public static final String VIEW_BEAN_NAME = "mtUserGroupView";
  public static final String DTO_BEAN_NAME  = "mtUserGroupDTO";

  public static final int  MAX_NUMBER_OF_GROUPS = 2147483646;

  /**
   * Implements the action for viewing user's groups.
   * <p> <p>
   * @param mapping <code>ActionMapping</code> object used to select this instance
   * @param form Optional <code>ActionForm</code> bean for this request (if any)
   * @param request <code>HttpServletRequest</code> object to process
   * @param response <code>HttpServletResponse</code> object to process
   * <p> <p>
   * @return <code>ActionForward</code> instance describing where and how
   * control should be forwarded, or null if the response has already been completed
   * <p> <p>
   * @throws Exception if an error occurs
   */
  public ActionForward processExecute(ActionMapping mapping,
                                      ActionForm form,
                                      HttpServletRequest request,
                                      HttpServletResponse response)
                               throws Exception
  {
    try {
      ViewDynaBean view = new ViewDynaBean(VIEW_BEAN_NAME, mapping);
      request.setAttribute(VIEW_BEAN_NAME, view);
    
      List dtos = new ArrayList();
      UserUtils.setP(view, "groupList", dtos);

      long userId = ((Long) UserUtils.getP(form, "userId")).longValue();

      PortalVisitor agent = getPortalVisitor(request);
      Visitor loginVisitor = agent.getVisitor();
      // validate the user's group option
	  boolean hasUserAdminRole = isUserInRole(loginVisitor, UserProfile.USER_ADMIN);
	  boolean hasOrganizationAdminRole = UserProfile.isOrganizationAdmin(loginVisitor);
      if (!hasUserAdminRole && !hasOrganizationAdminRole && userId != loginVisitor.getId()) {
         request.setAttribute(Globals.ERROR_KEY, "error.group.noGroupAdmin");
         return mapping.findForward("failure");
      }

      String formattedName = UserUtils.getFormattedName(userId, getResources(request),
          getLocale(request));
      UserUtils.setP(view, "formattedName", formattedName);
      HashMap orgAdminsMap = new HashMap();
      if (hasUserAdminRole == false) {
        AccessManager accessMgr = AccessManager.instance();
        List orgAdmins = accessMgr.getOwnerObjectsForPrincipal((Principal)loginVisitor, UserProfile.ORGANIZATION_ADMIN);
        if (null != orgAdmins) {
          for (int j = 0; j < orgAdmins.size(); j++) {
            ACObjectID ac = (ACObjectID) orgAdmins.get(j);
            orgAdminsMap.put(ac.getObjectID().trim(), ac);
          }
        }
      }
      VisitorGroup[] groups = VisitorGroupManager.findAllGroupsVisitorBelongsTo(userId, MAX_NUMBER_OF_GROUPS);
      boolean isExisted = false;
	  if (null != groups) {
        for (int i = 0; i < groups.length; i++) {
          VisitorGroup group = groups[i];
          ViewDynaBean oneDto = new ViewDynaBean(DTO_BEAN_NAME, mapping);
          UserUtils.setP(oneDto, "name", group.getFriendlyName());
          UserUtils.setP(oneDto, "fqn", group.getFullyQualifiedName());
          dtos.add(oneDto);
          if (hasUserAdminRole == false) {
           boolean doFQN = false;
            List parents = new ArrayList(1);
            parents.add(group);
            parents.addAll(group.getParents(true));
            for (int j = 0; parents != null && j < parents.size(); j++) {
              VisitorGroup parent = (VisitorGroup)parents.get(j);
              if (orgAdminsMap.containsKey(parent.getFullyQualifiedName())) {
                doFQN = true;
				isExisted = true;
                break;
              }
            }
            UserUtils.setP(oneDto, "fqnLink", doFQN ? Boolean.TRUE : Boolean.FALSE);
          }
          else {
            UserUtils.setP(oneDto, "fqnLink", Boolean.TRUE);
          }
        }
      }
	  // visitor is not userAdmin, user is not equal to visitor id, visitor doesn't
      // have any member under his/her organization group
      if (!hasUserAdminRole && userId != loginVisitor.getId() && !isExisted) {
         request.setAttribute(Globals.ERROR_KEY, "error.group.noGroupAdmin");
         return mapping.findForward("failure");
      }
    }
    catch (Exception ex) {
      ex.printStackTrace();
      request.setAttribute(Globals.ERROR_KEY, "error.application");
      return mapping.findForward("failure");
    }
   

	return mapping.findForward("success");
  }
}
